<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">





  <link rel="alternate" href="/blog/atom.xml" title="Hexo" type="application/atom+xml">






<meta name="description" content="##一、使用预编译语言防止SQL注入 public boolean existsUser(User user) {     //1.获取连接对象      Connection con=DBCP.getCon();     //2.创建预编译对象      PreparedStatement st=null;      ResultSet set=null;      try {//? 占位符">
<meta property="og:type" content="article">
<meta property="og:title" content="Hexo">
<meta property="og:url" content="http://songhangfei.gitee.io/blog/2018/11/22/使用预编译语言与连接池/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="##一、使用预编译语言防止SQL注入 public boolean existsUser(User user) {     //1.获取连接对象      Connection con=DBCP.getCon();     //2.创建预编译对象      PreparedStatement st=null;      ResultSet set=null;      try {//? 占位符">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2018-10-11T13:17:22.570Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Hexo">
<meta name="twitter:description" content="##一、使用预编译语言防止SQL注入 public boolean existsUser(User user) {     //1.获取连接对象      Connection con=DBCP.getCon();     //2.创建预编译对象      PreparedStatement st=null;      ResultSet set=null;      try {//? 占位符">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://songhangfei.gitee.io/blog/2018/11/22/使用预编译语言与连接池/">





  <title> | Hexo</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
	<a href="http://songhangfei.gitee.io/blog" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Hexo</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://songhangfei.gitee.io/blog/blog/2018/11/22/使用预编译语言与连接池/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="John Doe">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hexo">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline"></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-11-22T16:27:13+08:00">
                2018-11-22
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>##一、使用预编译语言防止SQL注入</p>
<pre><code>public boolean existsUser(User user) {
    //1.获取连接对象
     Connection con=DBCP.getCon();
    //2.创建预编译对象
     PreparedStatement st=null;
     ResultSet set=null;
     try {//? 占位符
        st=con.prepareStatement(&quot;select name from user where name=?&quot;);
        //给预编译对象占位符进行赋值
        st.setString(1,user.getName());
        //执行预编译语句  返回一个ResultSet
        set=st.executeQuery();
        //遍历set集合
        while(set.next()){
          //执行到这里说明有名字
            return true;
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        //关闭所有连接
        DBCP.closeAll(con, st, set);
    }

    return false;
}
</code></pre><p>#####Statement的几种实现</p>
<p>Statement 对象用于将SQL语句发送到数据库中。<br>Statement每次执行SQL语句，数据库都要执行SQL语句的编译，最好用于仅执行一次查询并返回结果的情形</p>
<ul>
<li>1、执行静态SQL语句，通常通过Statement实例实现。 </li>
<li>2、执行动态SQL语句，通常通过PreparedStatement实例实现。 </li>
<li>3、执行数据库存储过程，通常通过CallableStatement实例实现。</li>
</ul>
<p>#####PreparedStatement与Statement有什么区别</p>
<ul>
<li>1、PreparedStatement能预编译，这条预编译的SQL查询语句能在将来的查询中重用，这样一来，它比Statement对象生成的查询速度更快。 </li>
<li>2、PreparedStatement可以写动态参数化的查询 </li>
<li>3、PreparedStatement可以防止SQL注入式攻击 </li>
<li>4、PreparedStatement查询可读性更好，追加条件的语句很乱 </li>
<li>5、PreparedStatement不允许一个占位符（？）有多个值</li>
</ul>
<p>##二、连接池的使用</p>
<p>不使用连接池时：</p>
<pre><code>conn= DriverManager.getConnection(url,username,password);
</code></pre><p>连接池的特性：</p>
<p>连接对象不是直接从DriverManager获取，而是从DataSource数据源对象获取，不同的数据源由不同的服务商提供</p>
<pre><code>常见的数据源有：
    dbcp Spring
    c3po Hibernate
    druid 阿里巴巴
操作步骤：
1、创建数据源对象
2、获取Connection连接
3、关闭Connection连接
</code></pre><p>#############示例代码：</p>
<pre><code>//加载属性文件 配置信息
private static Properties p = new Properties();
private static Connection conn;
//数据源，连接对象从这里获取
private static DataSource dataSource;
static{
    //加载器对象
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    //通过加载器对象获取一个输入流
    InputStream inStream = loader.getResourceAsStream(&quot;dbcp.properties&quot;);
    try {
        p.load(inStream);
        //通过工厂方法创建一个数据源对象，并将p中的配置信息传过去
        dataSource = BasicDataSourceFactory.createDataSource(p);
        //Class.forName(p.getProperty(&quot;driverClassName&quot;));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
//获取连接对象  通过数据源来获取数据库连接对象
public static Connection getConnection(){
    try {
            //conn = DriverManager.getConnection(p.getProperty(&quot;url&quot;), p.getProperty(&quot;username&quot;), p.getProperty(&quot;password&quot;));
            conn = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }return conn;
    }
</code></pre><p>########dbcp.properties内容：</p>
<pre><code>driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/world
username=root
password=123456
maxActive=10
#数据库驱动
driverClassName=com.mysql.jdbc.Driver
#数据库连接地址
url=jdbc:mysql://localhost:3306/world
#用户名
username=root
#密码
password=123456
#连接池的最大数据库连接数。设为0表示无限制
maxActive=30
#最大空闲数，数据库连接的最大空闲时间。超过空闲时间，数据库连
#接将被标记为不可用，然后被释放。设为0表示无限制
maxIdle=10
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制
maxWait=1000
#超过removeAbandonedTimeout时间后，是否进 行没用连接（废弃）的回收（默认为false，调整为true)
removeAbandoned=true
#超过时间限制，回收没有用(废弃)的连接（默认为 300秒，调整为180）
removeAbandonedTimeout=180
</code></pre>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/11/22/hello-world/" rel="next" title="Hello World">
                <i class="fa fa-chevron-left"></i> Hello World
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">John Doe</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">categories</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">tags</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">John Doe</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>

</html>
